package com.java.service.impl;

import com.github.pagehelper.PageHelper;
import com.java.entity.Teacher;
import com.java.entity.TeacherExample;
import com.java.mapper.TeacherMapper;
import com.java.service.TeacherService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public int insert(Teacher teacher) {
        return teacherMapper.insertSelective(teacher);
    }

    @Override
    public int incrPaperCount(Integer teacherId) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(teacherId);
        Integer count = teacher.getTeacherPaperCount();
        count = count == null ? 0 : count;
        teacher.setTeacherPaperCount(count + 1);
        return teacherMapper.updateByPrimaryKeySelective(teacher);
    }

    @Override
    public int delete(Integer teacherId) {
        return teacherMapper.deleteByPrimaryKey(teacherId);
    }

    @Override
    public int update(Teacher teacher) {
        return teacherMapper.updateByPrimaryKeySelective(teacher);
    }

    @Override
    public Teacher selectOne(Integer teacherId) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(teacherId);
        if (teacher == null) {
            throw new RuntimeException("teacher is null, teacherId=" + teacherId);
        }
        return teacher;
    }

    @Override
    public List<Teacher> selectAll() {
        return teacherMapper.selectByExample(null);
    }

    @Override
    public List<Teacher> selectByPage(Integer pageNum, Integer pageSize, Map<String, Object> map) {
        // count: true 查询总记录数 reasonable: true 把pageNum限制在合理范围内 pageSizeZero: false 如果pageSize=0, 不查询
        PageHelper.startPage(pageNum, pageSize, true, true, false);
        String teacherName = (String) map.remove("teacherName");
        TeacherExample teacherExample = new TeacherExample();
        if (StringUtils.hasText(teacherName)) {
            teacherExample.or().andTeacherNameLike("%" + teacherName + "%");
        }
        return teacherMapper.selectByExample(teacherExample);
    }

}
